package sk.ygor.xtemplate;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 * User: ygor
 * Date: 13.11.2005
 * Time: 16:07:24
 */
public class BlockTokenizer {

    private static Pattern templatePattern =
            Pattern.compile("(?:<!-- (BEGIN): ([^ \\.]+) -->)|(?:<!-- (END): ([^ \\.]+) -->)");

    Matcher matcher;
    int position;
    BlockToken buffer;
    String source;

    public BlockTokenizer(String source) {
        this.source = source;
        position = 0;
        matcher = templatePattern.matcher(source);
        buffer = null;
    }

    public BlockToken nextToken() {
        BlockToken result;
        if (buffer != null) {
            result = buffer;
            buffer = null;
            return result;
        }
        if (position == source.length()) {
            return null;
        }
        if (matcher.find()) {
            if (matcher.group(1) != null) {
                buffer = new BlockToken(BlockToken.BEGIN, matcher.group(2));
                result = new BlockToken(BlockToken.CONTENT, source.substring(position, matcher.start()));
                position = matcher.end();
            } else {
                buffer = new BlockToken(BlockToken.END, matcher.group(4));
                result = new BlockToken(BlockToken.CONTENT, source.substring(position, matcher.start()));
                position = matcher.end();
            }
        } else {
            result = new BlockToken(BlockToken.CONTENT, source.substring(position, source.length()));
            position = source.length();
        }
        return result;
    }


}
